package com.mujin.keji.collectionsystem.module.login.views;

import android.Manifest;
import android.arch.lifecycle.ViewModelProviders;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.telephony.TelephonyManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mujin.keji.collectionsystem.CcsApplication;
import com.mujin.keji.collectionsystem.Constant;
import com.mujin.keji.collectionsystem.R;
import com.mujin.keji.collectionsystem.base.BaseActivity;
import com.mujin.keji.collectionsystem.base.BaseDto;
import com.mujin.keji.collectionsystem.common.ErrorEnum;
import com.mujin.keji.collectionsystem.exception.ServerException;
import com.mujin.keji.collectionsystem.http.HttpUtils;
import com.mujin.keji.collectionsystem.module.login.dto.LoginDto;
import com.mujin.keji.collectionsystem.module.login.viewmodel.LoginViewModel;
import com.mujin.keji.collectionsystem.module.login.vo.LoginCollectionVo;
import com.mujin.keji.collectionsystem.module.login.vo.LoginVo;
import com.mujin.keji.collectionsystem.module.main.dto.QueryPhoneDto;
import com.mujin.keji.collectionsystem.module.main.viewmodel.MainViewModel;
import com.mujin.keji.collectionsystem.module.main.views.MainActivity;
import com.mujin.keji.collectionsystem.module.mypager.views.ValidationMyPhoneActivity;
import com.mujin.keji.collectionsystem.server.RecordServcie;
import com.mujin.keji.collectionsystem.utils.DialogUtils;
import com.mujin.keji.collectionsystem.utils.Dom4jUtil;
import com.mujin.keji.collectionsystem.utils.EmptyUtils;
import com.mujin.keji.collectionsystem.utils.SPUtil;
import com.mujin.keji.collectionsystem.utils.ToastUtils;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;

import okhttp3.Response;

/**
 * 登陆界面
 *
 * @author weishixiong
 * @Time 2018-03-21
 */
public class LoginActivity extends BaseActivity {
    private EditText etUsername;
    private EditText etPwd;
    private RelativeLayout rlLogin;
    private RelativeLayout rlCencelUser;
    private RelativeLayout rlCencelPwd;
    private RelativeLayout rlEyes;
    private LoginViewModel loginViewModel;
    private TextView tvLogin;
    private MainViewModel mainViewModel;
    private ImageView ivEyes;
    private ScrollView scrollView;


    //检测网络连接状态
    private ConnectivityManager manager;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        CcsApplication.addActivity(this);
        //重新登录的时候 把 服务停掉
        Intent intentService = new Intent(this, RecordServcie.class);
        stopService(intentService);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        CcsApplication.removeActivity(this);

    }

    @Override
    protected void createViewModel() {
        loginViewModel = ViewModelProviders.of(this).get(LoginViewModel.class);
        mainViewModel = ViewModelProviders.of(this).get(MainViewModel.class);
    }

    @Override
    public int intiLayout() {
        return R.layout.activity_login;
    }

    @Override
    public void initView() {
        etUsername = (EditText) findViewById(R.id.et_username);
        etPwd = (EditText) findViewById(R.id.et_pwd);
        rlLogin = (RelativeLayout) findViewById(R.id.rl_login);
        rlCencelUser = (RelativeLayout) findViewById(R.id.rl_cencel_user);
        rlCencelPwd = (RelativeLayout) findViewById(R.id.rl_cencel_pwd);
        rlEyes = (RelativeLayout) findViewById(R.id.rl_eyes);
        tvLogin = (TextView) findViewById(R.id.tv_login);
        ivEyes = (ImageView) findViewById(R.id.iv_eyes);
        scrollView = (ScrollView) findViewById(R.id.scrollView);
        rlLogin.setEnabled(false);
    }

    @Override
    public void initData() {
        etUsername.setText(SPUtil.getData(Constant.SP.USER_SP, Constant.SP.USER, String.class, ""));
        if (!TextUtils.isEmpty(etUsername.getText().toString())) {
            rlCencelUser.setVisibility(View.VISIBLE);
        } else {
            rlCencelUser.setVisibility(View.GONE);
        }

    }

    private boolean mbDisplayFlg;

    @Override
    public void initListener() {
        rlLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                loginViewModel.login(etUsername.getText().toString(), etPwd.getText().toString(), LoginActivity.this, LoginActivity.this);


            }
        });
        rlLogin.setOnClickListener(v -> login());
        etUsername.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (EmptyUtils.isNotEmpty(s.toString())) {
                    rlCencelUser.setVisibility(View.VISIBLE);
                } else {
                    rlCencelUser.setVisibility(View.GONE);
                }
                if (TextUtils.isEmpty(etUsername.getText().toString()) || TextUtils.isEmpty(etPwd.getText().toString())) {
                    tvLogin.setTextColor(Color.parseColor("#aaFFFFFF"));
                    rlLogin.setEnabled(false);
                } else {
                    tvLogin.setTextColor(Color.parseColor("#FFFFFF"));
                    rlLogin.setEnabled(true);
                }
            }
        });
        etPwd.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (EmptyUtils.isNotEmpty(s.toString())) {
                    rlCencelPwd.setVisibility(View.VISIBLE);
                    rlEyes.setVisibility(View.VISIBLE);
                } else {
                    rlCencelPwd.setVisibility(View.GONE);
                    rlEyes.setVisibility(View.GONE);
                }
                if (TextUtils.isEmpty(etUsername.getText().toString()) || TextUtils.isEmpty(etPwd.getText().toString())) {
                    tvLogin.setTextColor(Color.parseColor("#aaFFFFFF"));
                    rlLogin.setEnabled(false);
                } else {
                    tvLogin.setTextColor(Color.parseColor("#FFFFFF"));
                    rlLogin.setEnabled(true);
                }

            }
        });
        rlCencelUser.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                etUsername.setText(null);
            }
        });
        rlCencelPwd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                etPwd.setText(null);
            }
        });
        rlEyes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!mbDisplayFlg) {
                    // display password text, for example "123456"
                    etPwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    ivEyes.setImageResource(R.drawable.image_login_open);
                } else {
                    // hide password, display "."
                    etPwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    ivEyes.setImageResource(R.drawable.image_login_close);
                }
                etPwd.setSelection(etPwd.getText().toString().length());//将光标移至文字末尾
                mbDisplayFlg = !mbDisplayFlg;
                etPwd.postInvalidate();

            }
        });


    }

    /**
     * 登录
     */
    private void login() {
        if (TextUtils.isEmpty(etUsername.getText().toString())) {
            return;
        }
        if (TextUtils.isEmpty(etPwd.getText().toString())) {
            return;
        }

        getLoadingDialog().showDialog();


        new Thread() {
            @Override
            public void run() {
                super.run();
                loginViewModel.login(etUsername.getText().toString(), etPwd.getText().toString(), LoginActivity.this, LoginActivity.this);
                handLogin(loginViewModel.getLoginBaseLiveData());
            }
        }.start();

    }


    private String getLoginSession(LoginVo vo) {
        LoginCollectionVo loginCollectionVo = new LoginCollectionVo();
        loginCollectionVo.setAccount(vo.getUsername());
        loginCollectionVo.setPassword(vo.getPassword());
        loginCollectionVo.setMerchantId(Constant.Server.merchantId);
        loginCollectionVo.setPlatform(Constant.Server.platform);

        String loginCollectionJson = JSON.toJSON(loginCollectionVo).toString();
        try {
            Log.i(TAG, "请求参数loginCollectionJson:" + loginCollectionJson);
            Response response = HttpUtils.post(Constant.Server.ROOT_URL + "login/", loginCollectionJson);
            Log.i(TAG, "登陆接口返回response:" + response);
            if (null == response) {
                throw new ServerException(ErrorEnum.ERROR_10003);
            }
            String rtn = response.body().string();
            Log.i(TAG, "登陆接口返回内容:" + rtn);
            Document doc = DocumentHelper.parseText(rtn);
            JSONObject json = new JSONObject();
            Dom4jUtil.dom4j2Json(doc.getRootElement(), json);
            JSONObject jsonObjectTemp = (JSONObject) json.get("data");
            try {
                return jsonObjectTemp.get("session") + "";
            } catch (Exception e) {
                throw new ServerException(ErrorEnum.ERROR_10003);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 处理登陆数据
     *
     * @param loginDtoBaseDto
     */
    private void handLogin(BaseDto<LoginDto> loginDtoBaseDto) {
        getLoadingDialog().dismiss();
        Constant.Server.isLoginRequest = false;
        if (loginDtoBaseDto.getCode() == Constant.Server.SUCCESS_CODE) {
            SPUtil.putData(Constant.SP.SP, Constant.SP.LOGIN_KEY, loginDtoBaseDto.getData());
            SPUtil.putData(Constant.SP.USER_SP, Constant.SP.USER, loginDtoBaseDto.getData().getUserAccount());
            String needSys = loginDtoBaseDto.getData().getNeedSysData();
            Message message = Message.obtain();
            message.what = 200;
            message.obj = needSys;
            handler.sendMessage(message);

        }
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 200) {
                //刷新列视图
                getLoadingDialog().dismiss();
                //刷新列视图
//                ToastUtils.showToast("登录成功,正在同步数据...");
                Log.e(TAG, "handleMessage: 登录成功跳转" );
                Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                intent.putExtra("needSys", (String) msg.obj);
                startActivity(intent);
            } else {
                getLoadingDialog().dismiss();
                Log.e(TAG, "handleMessage: 登录失败" );
                ToastUtils.showToast((String) msg.obj);

            }
        }
    };

    public Handler getHandler() {
        return handler;
    }

    public void setHandler(Handler handler) {
        this.handler = handler;
    }






    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finish();
            CcsApplication.clearAllActivitys();
            System.exit(0);
        }
        return false;
    }


}
